﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace SnippetBox.Core.Common.Caching {
    public class CacheService {
        public static TimeSpan DefaultExpiration = TimeSpan.FromMinutes(60);

        public CacheService() {
            Enabled = true;
        }

        public CacheService(bool enabled) {
            Enabled = enabled;
        }

        public bool Enabled { get; private set; }

        #region ICacheService Members

        public T Get<T>(string cacheId, Func<T> getItemCallback) where T : class {
            return Get(cacheId, getItemCallback, DefaultExpiration);
        }

        public T Get<T>(string cacheId, Func<T> getItemCallback, TimeSpan expiration) where T : class {
            return Get(cacheId, getItemCallback, Cache.NoAbsoluteExpiration, expiration);
        }

        public T Get<T>(string cacheId, Func<T> getItemCallback, DateTime expiration) where T : class {
            return Get(cacheId, getItemCallback, expiration, Cache.NoSlidingExpiration);
        }

        public T Get<T>(string cacheId, Func<T> getItemCallback, DateTime expirationDate, TimeSpan expirationTimeSpan) where T : class {
            var item = HttpRuntime.Cache.Get(cacheId) as T;
            if (item == null || (!Enabled)) {
                item = getItemCallback();

                if (item != null)
                    HttpContext.Current.Cache.Insert(cacheId, item, null, expirationDate, expirationTimeSpan);
            }
            return item;
        }

        public void Remove(string cacheId) {
            if (HttpRuntime.Cache.Get(cacheId) != null)
                HttpRuntime.Cache.Remove(cacheId);
        }

        public void RemoveAll(string cacheIdStartsWith) {
            IDictionaryEnumerator cacheItems = HttpRuntime.Cache.GetEnumerator();

            while (cacheItems.MoveNext()) {
                if (cacheItems.Key.ToString().StartsWith(cacheIdStartsWith))
                    HttpRuntime.Cache.Remove(cacheItems.Key.ToString());
            }
        }

        public Dictionary<string, object> GetAll() {
            IDictionaryEnumerator cacheItems = HttpRuntime.Cache.GetEnumerator();
            Dictionary<string, object> result = new Dictionary<string, object>(HttpRuntime.Cache.Count);

            while (cacheItems.MoveNext()) {
                result.Add(cacheItems.Key.ToString(), cacheItems.Value);
            }

            return result;
        }

        #endregion
    }
}
